package com.gin.kotlin.no_gay_alliance.activity

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageButton
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.widget.AppCompatButton
import androidx.viewbinding.ViewBinding
import androidx.viewpager2.widget.ViewPager2
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.PostActivity.PostResult
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.base.IntRangeTextWatcher
import com.gin.kotlin.no_gay_alliance.databinding.DialogPagerBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import java.util.Locale

/**
 * 抽象类，包含 ViewPager2 ，及右下角三个浮动按钮，划动时控制按钮显示和隐藏
 * @param T:ViewBinding
 */
abstract class AbstractPagerListActivity<T : ViewBinding> : AbstractBindingActivity<T>(), View.OnClickListener, ActivityResultCallback<ActivityResult> {
    /**
     * 启动器，对应发帖按钮功能
     */
    private lateinit var launcher: ActivityResultLauncher<Intent>

    /**
     * 发帖按钮：实际作用为发布新主题或回复
     */
    private var floatButtonPost: ImageButton? = null

    /**
     * 翻页按钮
     */
    private var floatButtonPager: AppCompatButton? = null

    /**
     * 刷新按钮
     */
    private var floatButtonRefresh: ImageButton? = null

    /**
     * 主题列表页，或回复列表页
     */
    private var viewPager2: ViewPager2? = null

    /**
     * 当前页
     */
    protected var currentPage = 1

    /**
     * 总页数
     */
    protected var totalPage = 1

    override fun onStart() {
        super.onStart()

        this.viewPager2 = b?.root?.findViewById(R.id.view_pager2)
        this.floatButtonPost = b?.root?.findViewById<ImageButton>(R.id.float_button_post)?.also { it.setOnClickListener(this) }
        this.floatButtonPager = b?.root?.findViewById<AppCompatButton>(R.id.float_button_pager)?.also { it.setOnClickListener(this) }
        this.floatButtonRefresh = b?.root?.findViewById<ImageButton>(R.id.float_button_refresh)?.also { it.setOnClickListener(this) }
        this.launcher = registerLauncher(this)

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_MOVE -> {
                val dy = ev.y.toInt() - startY
                if (dy < -100) {
                    // 隐藏按钮
                    listOfNotNull(
                        this.floatButtonPost,
                        this.floatButtonPager,
                        this.floatButtonRefresh,
                    ).filter { it.visibility != View.GONE }.forEach { it.visibility = View.INVISIBLE }

                } else if (dy > 100) {
                    // 显示按钮
                    listOfNotNull(
                        this.floatButtonPost,
                        this.floatButtonPager,
                        this.floatButtonRefresh,
                    ).filter { it.visibility != View.GONE }.forEach { it.visibility = View.VISIBLE }
                }
            }

        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.float_button_post -> launchPostActivity(launcher)
            R.id.float_button_refresh -> refresh()
            R.id.float_button_pager -> floatButtonPagerOnclick(this, currentPage, totalPage) {
                updatePage(it)
                viewPager2?.setCurrentItem(it - 1, false)
            }
        }
    }

    /**
     * 更新页码数据
     * @param currentPage Int?
     * @param totalPage Int?
     */
    fun updatePage(currentPage: Int? = null, totalPage: Int? = null) {
        Log.i(TAG, "updatePage: $currentPage / $totalPage")
        this.currentPage = currentPage ?: this.currentPage
        this.totalPage = totalPage ?: this.totalPage
        // 更新翻页按钮文字
        ui { floatButtonPager?.text = String.format(Locale.CHINESE, "%d/%d", this.currentPage, this.totalPage) }
    }

    override fun onActivityResult(result: ActivityResult) {
        handlePostResult(
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                result.data?.getParcelableExtra(PostResult::class.java.simpleName, PostResult::class.java)
            } else {
                result.data?.getParcelableExtra(PostResult::class.java.simpleName)
            }
        )
    }

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == HandlerMessageWhat.PAGE_UPDATED.ordinal) {
            Log.i(TAG, "页码信息更新: ${msg.arg1}/${msg.arg2}")
            // 如果当前页大于0更新当前页，如果最大页大于当前更新最大页
            updatePage(msg.arg1.takeIf { it > 0 }, msg.arg2.takeIf { it > this.totalPage })
        }
        return super.handleMessage(msg)
    }

    /**
     * 刷新：调用当前Fragment的刷新方法
     */
    abstract fun refresh()

    /**
     * 启动发帖活动
     * @param launcher ActivityResultLauncher<Intent>
     */
    abstract fun launchPostActivity(launcher: ActivityResultLauncher<Intent>)

    /**
     * 处理发帖结果
     * @param postResult PostResult
     */
    open  fun handlePostResult(postResult: PostResult?){}


    companion object {
        /**
         * 翻页悬浮按钮点击事件
         * @param context Context
         * @param currentPage Int
         * @param totalPage Int
         * @param onSetPage 执行跳转页数
         */
        fun floatButtonPagerOnclick(context: Context, currentPage: Int, totalPage: Int, onSetPage: (page: Int) -> Unit) {
            val pagerBinding = DialogPagerBinding.inflate(LayoutInflater.from(context))
            // 设置初始值和 TextWatcher
            val editText = pagerBinding.editText
            editText.setText(currentPage.toString())
            editText.addTextChangedListener(IntRangeTextWatcher(editText, 1, totalPage))
            editText.requestFocus()
            editText.setSelection(0, editText.text.length)
            pagerBinding.tvTipsSelectPage.text = context.getString(R.string.tv_tips_select_page, totalPage.toString())

            val dialogListener: (dialog: DialogInterface, which: Int) -> Unit = { _, which ->
                // 目标页数
                val page = when (which) {
                    DialogInterface.BUTTON_POSITIVE -> editText.text.toString().toInt()
                    DialogInterface.BUTTON_NEGATIVE -> totalPage
                    DialogInterface.BUTTON_NEUTRAL -> 1
                    else -> throw RuntimeException("非法输入")
                }
                onSetPage(page)
            }
            AlertDialogUtils.builder(context, contentView = pagerBinding.root, listener = dialogListener)
                .setNegativeButton(R.string.alert_bottom_last_page, dialogListener)
                .setNeutralButton(R.string.alert_bottom_first_page, dialogListener)
                .show()

            // 延时激活输入法
            App.INSTANCE.handler?.postDelayed({ InputMethodUtils.show(editText) }, 300)
        }

    }
}